package com.xu.cloud.common.process.support;

import com.xu.cloud.common.pojo.http.req.BaseRequest;
import com.xu.cloud.common.process.AbsXuApiFactoryBean;
import com.xu.cloud.common.process.IProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 基于jdk动态代理, 创建FactoryBean
 *
 * @author xuguan
 * @since 2025/1/20
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class XuApiJdkProxyFactoryBean<T> extends AbsXuApiFactoryBean<T> implements InvocationHandler {

    @Override
    protected T getProxy() {
        return (T) (Proxy.newProxyInstance(getTarget().getClassLoader(), new Class[]{getTarget()}, this));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (args != null && args.length == 1 && BaseRequest.class.isAssignableFrom(args[0].getClass())) {
            final IProcessor processor = getProcessSelector().select(method);
            return processor.process((BaseRequest) args[0]);
        }
        return method.invoke(getTarget(), args);
    }
}
